package com.duojuhe.coremodule.notice.service.impl;

import com.duojuhe.common.annotation.DataScopeFilter;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.constant.DataScopeConstants;
import com.duojuhe.common.enums.SystemEnum;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.notice.entity.NoticeCategory;
import com.duojuhe.coremodule.notice.entity.NoticeInfo;
import com.duojuhe.coremodule.notice.mapper.NoticeCategoryMapper;
import com.duojuhe.coremodule.notice.mapper.NoticeInfoMapper;
import com.duojuhe.coremodule.notice.pojo.dto.noticeinfo.*;
import com.duojuhe.coremodule.notice.service.NoticeInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class NoticeInfoServiceImpl extends BaseService implements NoticeInfoService {
    @Resource
    private NoticeCategoryMapper noticeCategoryMapper;
    @Resource
    private NoticeInfoMapper noticeInfoMapper;
    /**
     * 【通知公告详情】根据通知公告发布ID获取通知公告详情
     * @param req
     * @return
     */
    @Override
    public ServiceResult<QueryNoticeInfoRes> queryNoticeInfoResByNoticeId(NoticeInfoIdReq req) {
        QueryNoticeInfoRes noticeInfoRes = noticeInfoMapper.queryNoticeInfoResByNoticeId(req.getNoticeId());
        if (noticeInfoRes==null){
            throw new DuoJuHeException(ErrorCodes.PARAM_ERROR);
        }
        return ServiceResult.ok(noticeInfoRes);
    }

    /**
     * 【分页查询通知公告发布list】分页查询通知公告发布list
     * @param req
     * @return
     */
    @DataScopeFilter
    @Override
    public ServiceResult<PageResult<List<QueryNoticeInfoPageRes>>> queryNoticeInfoPageResList(QueryNoticeInfoPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,updateTime desc,createTime desc, noticeId desc");
        List<QueryNoticeInfoPageRes> list = noticeInfoMapper.queryNoticeInfoPageResList(req);
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 【分页查询我发布的list】分页查询我发布的list
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.SELF_DATA)
    @Override
    public ServiceResult<PageResult<List<QueryMyNoticeInfoPageRes>>> queryMyNoticeInfoPageResList(QueryMyNoticeInfoPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,updateTime desc,createTime desc, noticeId desc");
        List<QueryMyNoticeInfoPageRes> list = noticeInfoMapper.queryMyNoticeInfoPageResList(req);
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 【保存】通知公告发布通知公告
     * @param req
     * @return
     */
    @Override
    public ServiceResult saveNoticeInfo(SaveNoticeInfoReq req) {
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //检查分类
        checkNoticeInfoCategoryId(req.getCategoryId(),userTokenInfoVo.getTenantId());
        //当前时间
        Date nowDate = new Date();
        //通知公告id
        String noticeId = UUIDUtils.getUUID32();
        //构建信息对象
        NoticeInfo noticeInfo = new NoticeInfo();
        noticeInfo.setNoticeId(noticeId);
        noticeInfo.setCategoryId(req.getCategoryId());
        noticeInfo.setNoticeTitle(req.getNoticeTitle());
        noticeInfo.setNoticeContent(req.getNoticeContent());
        noticeInfo.setSort(req.getSort());
        noticeInfo.setCreateTime(nowDate);
        noticeInfo.setCreateDeptId(userTokenInfoVo.getCreateDeptId());
        noticeInfo.setCreateUserId(userTokenInfoVo.getUserId());
        noticeInfo.setTenantId(userTokenInfoVo.getTenantId());
        noticeInfo.setUpdateTime(nowDate);
        noticeInfo.setUpdateUserId(userTokenInfoVo.getUserId());
        //设置允许查询权限
        noticeInfo.setDataAllowAuth(SystemEnum.DATA_ALLOW_AUTH.ALL_AUTH.getKey());
        noticeInfoMapper.insertSelective(noticeInfo);
        return ServiceResult.ok(noticeId);
    }

    /**
     * 【修改】通知公告发布通知公告
     * @param req
     * @return
     */
    @Override
    public ServiceResult updateNoticeInfo(UpdateNoticeInfoReq req) {
        NoticeInfo noticeInfo = noticeInfoMapper.selectByPrimaryKey(req.getNoticeId());
        if (noticeInfo==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(noticeInfo.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //检查分类
        checkNoticeInfoCategoryId(req.getCategoryId(),noticeInfo.getTenantId());
        //当前时间
        Date nowDate = new Date();
        NoticeInfo updateNoticeInfo = new NoticeInfo();
        updateNoticeInfo.setNoticeId(noticeInfo.getNoticeId());
        updateNoticeInfo.setCategoryId(req.getCategoryId());
        updateNoticeInfo.setNoticeTitle(req.getNoticeTitle());
        updateNoticeInfo.setNoticeContent(req.getNoticeContent());
        updateNoticeInfo.setSort(req.getSort());
        updateNoticeInfo.setUpdateTime(nowDate);
        updateNoticeInfo.setUpdateUserId(userId);
        //设置允许查询权限
        updateNoticeInfo.setDataAllowAuth(SystemEnum.DATA_ALLOW_AUTH.ALL_AUTH.getKey());
        noticeInfoMapper.updateByPrimaryKeySelective(updateNoticeInfo);
        return ServiceResult.ok(noticeInfo.getNoticeId());
    }

    /**
     * 【彻底删除】根据通知公告发布ID彻底删除通知公告发布，注意一次仅能彻底删除一个通知公告发布
     * @param req
     * @return
     */
    @Override
    public ServiceResult deleteNoticeInfoByNoticeId(NoticeInfoIdReq req) {
        NoticeInfo noticeInfo = noticeInfoMapper.selectByPrimaryKey(req.getNoticeId());
        if (noticeInfo==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(noticeInfo.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //删除信息
        noticeInfoMapper.deleteByPrimaryKey(noticeInfo.getNoticeId());
        return ServiceResult.ok(noticeInfo.getNoticeId());
    }

    /**
     * 【私有方法，辅助其他接口方法使用】 检查分类是否存在
     */
    private void checkNoticeInfoCategoryId(String categoryId,String tenantId) {
        if (StringUtils.isBlank(categoryId)){
            throw new DuoJuHeException(ErrorCodes.NOTICE_CATEGORY_NOT_EXIST);
        }
        NoticeCategory category = noticeCategoryMapper.selectByPrimaryKey(categoryId);
        if(category==null || !tenantId.equals(category.getTenantId())){
            throw new DuoJuHeException(ErrorCodes.NOTICE_CATEGORY_NOT_EXIST);
        }
    }
}
